#include <Arduino.h>
#include <ESP8266WiFi.h>

#include <PubSubClient.h>


int pin1=5;

WiFiClient eclient;

PubSubClient client(eclient);


void setup_wifi(){

  WiFi.begin("wifi","wifi密码");
  Serial.print("正在连接wifi");
  while (WiFi.status()!=WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println(WiFi.localIP());

}

void callback(char* topic, byte* payload, unsigned int length) {
  // handle message arrived
  Serial.println(topic);

  String cmd="";
  for (int i = 0; i < length; i++)
  {
     cmd+=(char)payload[i];
  }
  Serial.println(cmd);
  
  String _topic(topic);
  if(_topic.equals("light")){
    if(cmd.equals("on")){
      digitalWrite(pin1,LOW);
    }else if (cmd.equals("off"))
    {
      digitalWrite(pin1,HIGH);
    }
    
  }

}

void connent(){
  while (!client.connected())
  {
     Serial.print(".");
     if(client.connect("esp826601")){
       client.publish("online","hello word");
       client.subscribe("light");
     }
  }
  
  
}


void setup() {
  
  pinMode(pin1,OUTPUT);

  digitalWrite(pin1,HIGH);

  Serial.begin(115200);

  setup_wifi();

  client.setServer("10.20.0.155",1883);
  client.setCallback(callback);

  connent();

}

void loop() {
  client.loop();
}